﻿function buildFormValidator(formGuid, rules, messages) {
    var formCssId = "#form-" + formGuid;
    var containter = $(formCssId + " .errorList");

    $(formCssId).validate({
        errorContainer: containter,
        errorLabelContainer: $("ul", containter),
        wrapper: 'li',
        meta: "validate",
        rules: rules,
        messages: messages,
        submitHandler: function (form) {
            $(formCssId + " .formLoading").show("fast");

            var url = "/base/submitContourForm/CreateRecord/";
            var queryString = $(formCssId).formSerialize();
            var queryString = queryString + "&formGuid=" + formGuid;

            $.post(url, queryString,
            function (data) {
                hideForm(formCssId);

                try {
                    var response = eval("(" + data + ")");

                    if (response.success == "true" == false) {
                        showEnabledForm(formCssId);
                        var errors = serverSideErrorsObject(response);
                        $(formCssId).validate().showErrors(errors);
                    } else {
                        $(formCssId + " .formPosted").show("fast").removeClass("error");
                    }
                } catch (e) {
                    showGenericError(formCssId);
                }
            });
        }
    });
}

function showGenericError(formCssId) {
    $(formCssId + " ul.errorList").html("<li>Something went wrong while sending the form. Please try again.</li>");
    $(formCssId + " li.errorList").show();
    $(formCssId + " ul.errorList").show();
    showEnabledForm(formCssId);
}

function showEnabledForm(formCssId) {
    $(formCssId + " .formPosted").hide("fast");
    $(formCssId + " .formArea").show("fast");
    $(formCssId + " .button").attr("enabled", true);
}

function hideForm(formCssId) {
    $(formCssId + " .formArea").hide("fast");
    $(formCssId + " .formLoading").hide("fast");
}

function serverSideErrorsObject(response) {
    var errorString = "";
    for (i = 0; i < response.errors.length; i++) {
        if (i != 0) {
            ", "
        }
        errorString = errorString + "{ \"" + response.errors[0].field + "\": " + "\"" + response.errors[0].errorMessage + "\" }";
    }

    var errors = eval("(" + errorString + ")");
    return errors;
}

$(function () {
    $.validator.addMethod(
        "regex",
        function (value, element, regexp) {
            if (regexp.constructor != RegExp)
                regexp = new RegExp(regexp);
            else if (regexp.global)
                regexp.lastIndex = 0;
            return this.optional(element) || regexp.test(value);
        },
        "This is not a valid value"
    );
});